package cn.ljw_jhc.booksearch;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by info on 16/12/22.
 */
public class ThumbnailDownloader extends HandlerThread {

    private static final String TAG = "ThumbnailDownloader";
    public static final int DOWNLOAD_IMAGE =  1;
    private Handler downloaderHandler;
    private OnThumbnailDownloaded listener;

    private ConcurrentHashMap<String,BookSearchFragment.BookHolder> map =new ConcurrentHashMap<>();

    public ThumbnailDownloader() {
        super(TAG);
    }

    public interface OnThumbnailDownloaded{
        public void onThumbnailDownloaded(Bitmap image, BookSearchFragment.BookHolder holder);
    }

    public void setListener(OnThumbnailDownloaded listener) {
        this.listener = listener;
    }

    @Override
    protected void onLooperPrepared() {
        super.onLooperPrepared();
        downloaderHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == DOWNLOAD_IMAGE){
                    try {
                        String imageUrl = (String) msg.obj;
                        byte[] imageBytes = new DoubanFetcher().getURL(imageUrl);
                        Bitmap movieBitmap = BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length);
                        listener.onThumbnailDownloaded(movieBitmap,map.get(imageUrl));
                        Log.d(TAG,imageUrl);
                    } catch (IOException e) {
                        Log.e(TAG,"fetch image error.",e);
                    }
                }
            }
        };

    }

    public void queueDownloader(BookSearchFragment.BookHolder holder,String imageURL){
        map.put(imageURL,holder);
        Message msg = new Message();
        msg.what = DOWNLOAD_IMAGE;
        msg.obj = imageURL;
        downloaderHandler.sendMessage(msg);
    }
}
